#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>

int main()
{
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    if (n != 0)
    {
        std::cerr << "pipe error" << std::endl;
        return 1;
    }
    pid_t id = fork();
    if (id == 0)
    {
        close(pipefd[0]);
        int cnt = 0;
        int total = 0;
        while (true)
        {
            //std::string message = "hello world";
            std::string message = "h";
            // message += std::to_string(getpid());
            // message += ",";
            // message += std::to_string(cnt++);
            total += ::write(pipefd[1],message.c_str(),message.size());
            std::cout << "total: " << total << std::endl;//验证管道的大小，ubuntu中大小为64KB
            //sleep(1);
            //break;
        }
        exit(0);
    }
    else if (id > 0)
    {
        char buffer[1024];
        close(pipefd[1]);
        while (true)
        {
            sleep(5);
            ssize_t n = ::read(pipefd[0], buffer, 1024);
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << "child->father,message: " << buffer << std::endl;
            }
            else if(n == 0) 
            {
                // 如果写端关闭
                // 读端读完管道内部的数据，在读取的时候，
                // 就会读取到返回值0，表示对端关闭，也表示读到文件结尾
                std::cout << "n : " << n << std::endl;
                std::cout << "child quit,me too" << std::endl;
                break;
            }
            //::close(pipefd[0]);
            //break;
        }
        // sleep(5);
        int status;
        pid_t wid = ::waitpid(id,&status,0);
        std::cout << "wait success，wid : " << id << "，exit code : " << ((status >> 8) & 0xFF) \
        << "，exit sig : " << (status & 0x7F) << std::endl;
    }
    else
    {
        std::cerr << "fork erro" << std::endl;
        return 2;
    }
}